<template>
  <ContentWrap>
    <h2 class="fonts24 fontw500">用户管理</h2>
    <div class="flex justify-between">
      <div class="">
        <ElButton type="primary" :icon="Plus" @click="onAdd">
          {{ t('新增用户') }}
        </ElButton>
      </div>
      <div class="">
        <ElInput v-model="state.keywords" style="width: 266px;height: 32px;margin-right: 10px;" placeholder="用户姓名/手机号"
          :prefix-icon="Search" />
        <ElButton type="primary" :icon="Search" @click="onSearch">
          {{ t('common.query') }}
        </ElButton>
        <ElButton :icon="Refresh" @click="onReset">
          {{ t('common.reset') }}
        </ElButton>
      </div>
    </div>
    <div class="" style="margin-top: 25px;">
      <Table v-model:pageSize="pageSize" v-model:currentPage="currentPage" :columns="allSchemas.tableColumns"
        :data="dataList" :loading="loading" :pagination="{ total: total }" @register="tableRegister"
        :headerCellStyle="headerCellStyle" :rowStyle="rowStyle" />
    </div>
  </ContentWrap>
  <Dialog v-model="dialogVisible1" :title="state.dialogVisible1title" width="500">
    <el-form ref="ruleFormRef" :model="state.ruleForm" :rules="rules" label-width="120px" class="demo-ruleForm"
      status-icon>
      <el-form-item label="账号类型" prop="roleId">
        <el-select v-model="state.ruleForm.roleId" placeholder="请选择账号类型">
          <el-option :label="item.roleName" :value="item.roleId" v-for="(item, index) in state.ruleOptions"
            :key="index" />

        </el-select>
      </el-form-item>
      <el-form-item label="用户姓名" prop="nickName">
        <el-input v-model="state.ruleForm.nickName" placeholder="请输入用户姓名" />
      </el-form-item>
      <el-form-item label="用户账号" prop="userName">
        <el-input v-model="state.ruleForm.userName" placeholder="请输入账号" />
      </el-form-item>
      <el-form-item label="用户密码" prop="password">
        <el-input v-model="state.ruleForm.password" show-password type="password" placeholder="请输入密码"
          :disabled="state.dialogVisible1title == '编辑用户'" />
      </el-form-item>
      <el-form-item label="手机号码" prop="phonenumber">
        <el-input v-model="state.ruleForm.phonenumber" placeholder="请输入手机号" />
      </el-form-item>
      <el-form-item label="邮箱地址" prop="email">
        <el-input v-model="state.ruleForm.email" placeholder="请输入邮箱地址" />
      </el-form-item>
      <el-form-item label="负责部门" prop="deptId">
        <el-cascader collapse-tags max-collapse-tags="2" placeholder="请选择所属部门" v-model="state.ruleForm.deptId"
          :options="state.departmentOption" :props="props1" clearable />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="flex ">
        <ElButton @click="resetForm(ruleFormRef)">{{ t('dialogDemo.cancel') }}</ElButton>
        <ElButton type="primary" :loading="loadingAdd" @click="submitForm(ruleFormRef)">{{ t('dialogDemo.sure') }}
        </ElButton>
      </div>
    </template>
  </Dialog>
  <!-- 删除框 -->
  <Adetele :title="state.deteleTitle" @deteleClick="deteleClick" :deteleBool="state.deteleBool" />
  <!-- 重置密码框 -->
  <Areact :title="state.deteleTitle" @deteleClick="deteleClick" :deteleBool="state.reactBoolean"
    :password="state.password" />
</template>
  
<script setup lang="tsx">
import { deptTreeList } from "@/api/organizational/index"
import { Table } from '@/components/Table'
import { useTable } from '@/hooks/web/useTable'
import { Search, Plus, Refresh, Pointer, Star } from '@element-plus/icons-vue'
import { Form, FormSchema } from '@/components/Form'
import { Dialog } from '@/components/Dialog'
import { useEmitt } from '@/hooks/event/useEmitt'
import { ElButton, ElInput, ElMessage } from 'element-plus'
// import { propTypes } from '@/utils/propTypes'
import { useI18n } from '@/hooks/web/useI18n'
import { ContentWrap } from '@/components/ContentWrap'
import { ref, reactive, unref } from "vue"
import { CrudSchema, useCrudSchemas } from '@/hooks/web/useCrudSchemas'
import { useForm } from '@/hooks/web/useForm'
import { useValidator } from '@/hooks/web/useValidator'
import { Adetele } from "../Components/Adetele/index"
import { Areact } from "../Components/Areact/index"
import { list, add_new, edit_user, reset_pwd, del, rolelist } from "@/api/admin/index"
import { formatToDateTime } from "@/utils/dateUtil"
const { required } = useValidator()
const { formRegister, formMethods } = useForm()
const { getElFormExpose } = formMethods
const { t } = useI18n()
const dialogVisible1 = ref(false)
const props1 = {
  // multiple: true,
  emitPath: false,
  checkStrictly: true,
  value: "id",
  label: "label"
}
const state = reactive({
  departmentOption: [],
  dialogVisible1title: "",
  inputSearch: "",
  schema: [
    {
      field: 'field1',
      label: t('部门'),
      component: 'Select',
      componentProps: {
        options: [
          {
            label: 'option1',
            value: '1'
          },
          {
            label: 'option2',
            value: '2'
          }
        ],
        on: {
          change: (value: string) => {
            console.log(value)
          }
        }
      }
    },
    {
      field: 'field2',
      label: t('性别'),
      component: 'Select',
      componentProps: {
        options: [
          {
            label: 'option1',
            value: '1'
          },
          {
            label: 'option2',
            value: '2'
          }
        ],
        on: {
          change: (value: string) => {
            console.log(value)
          }
        }
      }
    }
  ] as any,
  deteleData: {} as any,
  deteleBool: false,
  deteleTitle: "",
  reactBoolean: false,//重置
  password: "",
  ruleForm: {} as any,
  keywords: "",
  departments: [],
  react: false,
  delId: "",
  ruleOptions: [] as any,
})
// 表格基本信息
const crudSchemas = reactive<CrudSchema[]>([
  {
    field: 'nickName',
    label: t('用户姓名'),
  },
  {
    field: 'userName',
    label: t('账号'),
  },
  {
    field: 'phonenumber',
    label: t('手机号'),
    search: {
      hidden: true
    }
  },
  {
    field: 'email',
    label: t('邮箱'),
    search: {
      hidden: true
    }
  },
  {
    field: 'deptId',
    label: t('负责部门'),
    search: {
      hidden: true
    },
    table: {
      slots: {
        default: (data: any) => {
          return (
            <>
              <div>{data[0].row.dept.deptName || ''}</div>
            </>
          )
        }
      }
    }
  },
  {
    field: 'action',
    width: '260px',
    label: t('tableDemo.action'),
    search: {
      hidden: true
    },
    form: {
      hidden: true
    },
    detail: {
      hidden: true
    },
    table: {
      slots: {
        default: (data: any) => {
          return (
            <>
              <ElButton link type="primary" onClick={() => action(data[0].row)}>
                {t('编辑')}
              </ElButton>
              <ElButton link type="danger" onClick={() => delData(data[0].row)}>
                {t('删除')}
              </ElButton>
              {/* <ElButton link type="primary" onClick={() => receat(data[0].row)}>
                {t('重置密码')}
              </ElButton> */}
            </>
          )
        }
      }
    }
  }
])

const { tableRegister, tableState, tableMethods } = useTable({
  fetchDataApi: async () => {
    const { currentPage, pageSize } = tableState
    const res: any = await list({
      pageNum: state.react ? 1 : unref(currentPage),
      pageSize: unref(pageSize),
      searchValue: state.keywords
    })
    console.log(res);

    
    state.react = false
    return {
      list: res.rows,
      total: res.total
    }
  },
  fetchDelApi: async () => {
    const res = await delTableListApi(unref(ids))
    return !!res
  }
})
// 表格头部信息
const headerCellStyle: any = {
  "background": "#F2F6FC",
  "height": "48px"
}
// 
const rowStyle: any = {
  "height": "48px"
}
const { loading, dataList, total, currentPage, pageSize } = tableState

const { getList, getElTableExpose, delList } = tableMethods

// getList()
useEmitt({
  name: 'getList',
  callback: (type: string) => {
    if (type === 'add') {
      currentPage.value = 1
    }
    getList()
  }
})
const { allSchemas } = useCrudSchemas(crudSchemas)
const action = (row: any) => {
  console.log("编辑", row);
  dialogVisible1.value = true
  state.ruleForm = row
  state.ruleForm.department = row?.otherinfo?.department
  state.ruleForm.departments = row?.otherinfo?.departments
  state.ruleForm.password = "123456"
  state.dialogVisible1title = t('编辑用户')
}
const delData = (row: any) => {
  console.log("删除", row);
  state.delId = row.userId
  state.deteleTitle = "确认删除用户账号？"
  state.deteleBool = true
}
const receat = (row: any) => {
  console.log("重置", row);
  state.delId = row.id
  state.deteleTitle = "确认重置账号密码？"
  state.deteleBool = true
}
// 新增
const onAdd = () => {
  console.log("新增");
  state.ruleForm = {}
  dialogVisible1.value = true
  state.dialogVisible1title = t('新增用户')
}
const deteleClick = (val: any) => {
  console.log("父组件", val);
  state.deteleBool = false
  if (state.deteleTitle == "确认删除用户账号？") {
    if (val) {
      delApi(state.delId)
    } else {
      state.deteleBool = false
    }
  }
  // if (state.deteleTitle == "确认重置账号密码？") {
  //   if (val) {
  //     reset_pwdApi({ id: state.delId })
  //   }
  //   return
  // } else if (state.deteleTitle == "系统已将密码重置为") {
  //   state.reactBoolean = false
  //   return
  // }
}
// 导入
const ongonin = () => {
  console.log("导入");
}
// 查询
const onSearch = () => {
  console.log("查询");
  state.react = true
  getList()
}
// 重置
const onReset = () => {
  console.log("重置");
  state.keywords = ""
  state.react = true
  getList()
}
// 表单确定
const formSubmit = async () => {
  const elFormExpose = await getElFormExpose()
  elFormExpose?.validate((valid) => {
    if (valid) {
      console.log('submit success')
    } else {
      console.log('submit fail')
    }
  })
}
// 表单
// 校验规则
interface RuleForm {

}


var checkData = (rule, value, callback) => {
  if (value) {
    if (/[\u4E00-\u9FA5]/g.test(value)) {
      callback(new Error("密码不能输入汉字!"));
    } else {
      callback();
    }
  }
  callback();
};

const ruleFormRef = ref<FormInstance>()
const rules = reactive<FormRules<RuleForm>>({
  email:[{ required: true, message: '请输入邮箱地址', trigger: 'blur' },
    { type: 'email', message: '邮箱格式不正确', trigger: ['blur', 'change'] },],
  nickName: [
    { required: true, message: '请填写用户姓名', trigger: 'blur' },
    { min: 1, max: 50, message: '不超过50个字符', trigger: 'blur' },
  ],
  roleId: [
    { required: true, message: '请选择账号类型', trigger: 'blur' },
  ],
  userName: [
    { required: true, message: '请填写用户账号', trigger: 'blur' },
    { min: 1, max: 50, message: '不超过50个字符', trigger: 'blur' },
    { validator: checkData, trigger: "blur" },
  ],
  phonenumber: [
    { required: true, message: '请填写手机号', trigger: 'blur' },
    {
      pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
      message: "请输入正确的电话",
      trigger: "blur",
    },
  ],
  password: [
    { required: true, message: '请填写密码', trigger: 'blur' },
    { min: 1, max: 50, message: '不超过50个字符', trigger: 'blur' },
    { validator: checkData, trigger: "blur" },
    // {
    //   required: true,
    //   pattern:
    //     /^(?![a-zA-Z]+$)(?![A-Z0-9]+$)(?![A-Z\W_!@#$%^&*`~()-+=]+$)(?![a-z0-9]+$)(?![a-z\W_!@#$%^&*`~()-+=]+$)(?![0-9\W_!@#$%^&*`~()-+=]+$)[a-zA-Z0-9\W_!@#$%^&*`~()-+=]{8,20}$/,
    //   message: "包含大小写字母、数字和特殊字符的三种",
    //   trigger: "blur",
    // }
  ],
  deptId: [
    {
      required: true,
      message: '请选择部门',
      trigger: 'change',
    },
  ],

})
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      state.ruleForm.roleIds=[state.ruleForm.roleId]
      if (state.dialogVisible1title == '新增用户') {
       
        add_userApi(state.ruleForm)
      } else {
        edit_userApi(state.ruleForm)

      }
      console.log('submit!')
    } else {
      console.log('error submit!', fields)
    }
  })
}
const resetForm = (formEl: FormInstance | undefined) => {
  dialogVisible1.value = false
}
const departmentApi = async () => {
  await deptTreeList().then((res: any) => {
    console.log("部门", res);
    state.departmentOption = res.data.tree
    getList()
  }).catch(() => {

  })
}
const rolelistApi = async () => {
  await rolelist().then((res: any) => {
    console.log("角色", res);
    state.ruleOptions = res.rows
  }).catch(() => {

  })
}
departmentApi()
rolelistApi()
// 新增
const loadingAdd = ref(false)
const add_userApi = async (params) => {
  loadingAdd.value = true
  await add_new(params).then((res: any) => {
    if (res.code == 200) {
      console.log("保存", res);
      dialogVisible1.value = false
      loadingAdd.value = false
      getList()
      ElMessage.success(res.msg)
    }
  }).catch((res: any) => {
    ElMessage.error(res.msg)
    loadingAdd.value = false
  })
}
// 修改
const edit_userApi = async (params) => {
  loadingAdd.value = true
  await edit_user(params).then((res: any) => {
    if (res.code == 200) {
      console.log("保存", res);
      dialogVisible1.value = false
      loadingAdd.value = false
      getList()
      ElMessage.success(res.msg)
    }
  }).catch((res: any) => {
    ElMessage.error(res.msg)
    loadingAdd.value = false
  })
}
// 删除
const delApi = async (params) => {
  loadingAdd.value = true
  await del(params).then((res: any) => {
    console.log("保存", res);
    state.deteleBool = false
    ElMessage.success(res.msg)
    getList()
  }).catch((res: any) => {
    ElMessage.error(res.msg)
    loadingAdd.value = false
  })
}
// 修改
const reset_pwdApi = async (params) => {
  loadingAdd.value = true
  await reset_pwd(params).then((res: any) => {
    if (res.code == 200) {
      console.log("保存", res);
      state.password = res.data.new_pwd
      state.deteleTitle = "系统已将密码重置为"
      state.reactBoolean = true
      loadingAdd.value = false
    }
  }).catch((res: any) => {
    ElMessage.error(res.msg)
    loadingAdd.value = false
  })
}
</script>
  
<style lang="less" scoped>
h2 {
  position: relative;
  margin: 0;
  margin-bottom: 26px;

  &::after {
    position: absolute;
    left: -20px;
    top: 2px;
    content: "";
    width: 8px;
    height: 24px;
    background: #2F6CBC;
    border-radius: 0px 4px 4px 0px;
    opacity: 1;
  }
}
</style>